import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_my_web/widget/TextWidget.dart';

//使用RenderObjectWidget方式绘制
class SketchPad_4 extends LeafRenderObjectWidget{
  @override
  RenderObject createRenderObject(BuildContext context) {
    return SketchPad_4RenderBox();
  }

}
class SketchPad_4RenderBox extends RenderBox{
  static final pen = Paint()
    ..color=Colors.black
    ..strokeWidth=2.0;
  static final pen2 = Paint()
    ..color=Colors.grey
    ..strokeWidth=2.0;

  var _image;
  Picture? _picture;
  final _previous=Path();
  var _current=Path();

  @override
  void handleEvent(PointerEvent event,BoxHitTestEntry entry){

    if(event is PointerDownEvent){
      // print("PointerDownEvent");
      _current.moveTo(entry.localPosition.dx, entry.localPosition.dy);
    }else if(event is PointerMoveEvent){
      _current.lineTo(entry.localPosition.dx, entry.localPosition.dy);
      markNeedsPaint();
    }else if(event is PointerUpEvent){
      _previous.addPath(_current, Offset.zero);
      _current = Path();
      PictureRecorder recorder = PictureRecorder();
      Canvas canvas = Canvas(recorder);
      canvas.drawPath(_previous, pen2);
      recorder.endRecording().toImage(2000, 2000).then((img){
        _image = img;
        markNeedsPaint();
      }
      );
      // _picture = recorder.endRecording();
      // markNeedsPaint();
    }
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    // super.paint(context, offset);
    context.canvas.drawColor(Colors.green[100]!, BlendMode.srcATop);
    context.canvas.translate(offset.dx, offset.dy);
    if(_image!=null){
      context.canvas.drawImage(_image!,offset,pen2);
    }
    context.canvas.drawPath(_current, pen);
  }
  @override
  void performLayout() =>size = Size(constraints.maxWidth,constraints.maxHeight);
  @override
  bool hitTestSelf(Offset position) =>true;
  @override
  bool get isRepaintBoundary => true;
}
